package org.example.road.learn01;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.NettyRuntime;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.internal.SystemPropertyUtil;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.concurrent.ThreadFactory;

@Slf4j
public class OutMemoryError {

    private static final Integer CONNECTIONS = 100;

    private static final Integer THREADS = Math.max(1, SystemPropertyUtil.getInt(
            "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));

    public static void main(String[] args) {
        ThreadFactory threadFactory = new DefaultThreadFactory("clientthread");
        for (int i = 0; i < CONNECTIONS; i++) {
            Bootstrap bootstrap = new Bootstrap();
            NioEventLoopGroup loopGroup = new NioEventLoopGroup(THREADS, threadFactory);
            bootstrap.group(loopGroup);
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024);
            bootstrap.channel(NioSocketChannel.class);
            bootstrap.handler(new LoggingHandler(LogLevel.INFO));

            try {
                final ChannelFuture channelFuture = bootstrap.connect(new InetSocketAddress("localhost", 8080)).sync();
                log.info("服务连接成功");
                final Channel channel = channelFuture.channel();
                channel.closeFuture().addListener(new ChannelFutureListener() {
                    @Override
                    public void operationComplete(ChannelFuture future) throws Exception {
                        log.info("优雅关闭资源");
                        loopGroup.shutdownGracefully();
                    }
                });
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        log.info("main线程结束");
    }
}
